<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AddController extends CI_Controller {

    function index(){
        session_start();
        $_SESSION['uid']=$_GET['uid'];
        $data = array('uid'=>$_SESSION['uid']);

        $this->load->helper('url');
        $this->load->view('header', $data);
        $this->load->view('add_book');
        $this->load->view('footer');
    }

    function add(){
        session_start();

        $book_name = $_GET['book_name'];
        $douban_link = $_GET['douban_link'];
        $book_price = $_GET['book_price'];
        $user_comment = $_GET['user_comment'];

        $url_prefix = 'http://api.douban.com/book/subject/';
        $douban_apikey = '05f675cf1602fa9f11e3616d4208efdd';
        $array = preg_split("/\//", $douban_link);
        $book_no = $array[4];
        $url = $url_prefix.$book_no.'?apikey='.$douban_apikey.'&alt=json';

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $raw_data = curl_exec($ch);
        curl_close($ch);

        $arr = json_decode($raw_data, true);
        $title = $arr['title']['$t'];
        $author = '';
        foreach($arr['author'] as $value){
            $author .= ' '.$value['name']['$t'];
        }
        $publisher = '';
        foreach($arr['db:attribute'] as $value){
            if($value['@name'] == 'publisher'){
                $publisher = $value['$t'];
                break;
            }
        }
        $image_link = '';
        foreach($arr['link'] as $value){
            if($value['@rel'] == 'image'){
                $image_link = $value['@href'];
                break;
            }
        }

        $douban_comment = '完整书名：'. $title . '；作者：' . $author . '；出版社：' . $publisher;

        $user_id = $_SESSION['uid'];

        $data = array(
            'USER_ID'=>$user_id,
            'BOOK_NAME'=>$book_name,
            'DOUBAN_LINK'=>$douban_link,
            'IMAGE_LINK'=>$image_link,
            'BOOK_PRICE'=>$book_price,
            'DOUBAN_COMMENT'=>$douban_comment,
            'USER_COMMENT'=>$user_comment
        );
        $this->load->model('book_m');
        $this->book_m->insert($data);

        header('Content-Type:text/json');
        echo json_encode(true);
    }
}